package de.lindenvalley.sevmob;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import com.google.gson.Gson;

import de.lindenvalley.sevmob.model.InstallResult;
import de.lindenvalley.sevmob.network.ConnectInterface;
import de.lindenvalley.sevmob.network.HttpConnect;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

/**
 * Th main class of SDK
 * @author "Lindenvalley GmbH"
 * @
 *
 */
public class SevMobTracker {
	
	
	/**
	 * Context of main application
	 */
	private Context mContext;
	
	private SevMobDeviceInfo deviceInfo;
	
	private String deviceId;
	
	
	
	/**
	 * This is constructor for main tracker class
	 * @param context - Application's context
	 */
	public SevMobTracker(Context context) {
		this.mContext = context;
		Intent intent = new Intent(mContext.getString(R.string.ACTION_SERVICE));
		mContext.startService(intent);
		deviceInfo = new SevMobDeviceInfo(mContext);
	}
	
	/**
	 * Destroy Context, service and other data. Should be call on the finish application.
	 */
	public void destoy(){
		
		if (mContext != null){
			Intent intent = new Intent(mContext.getString(R.string.ACTION_SERVICE));
			mContext.stopService(intent);
			mContext = null;
		}
	}
	
	/**
	 * The method calls after applications will be install.
	 * @param referrer String that receive from Google Play.
	 * @return JSON string from server that contains device ID
	 */
	public String trackerInstall(String referrer){
		ConnectInterface connectInterface = new HttpConnect();
		List<NameValuePair> pairs = new ArrayList<NameValuePair>();
		pairs.add(new BasicNameValuePair("deviceid", deviceInfo.getDeviceId()));
		pairs.add(new BasicNameValuePair("screensize", deviceInfo.getScreenResolution()));
		pairs.add(new BasicNameValuePair("fingerprint", deviceInfo.getDeviceFingerprint()));
		pairs.add(new BasicNameValuePair("referrer", referrer));
		String result = connectInterface.post(mContext.getString(R.string.APP_INSTALL), pairs);
		Gson parser = new Gson();
		InstallResult installResult = parser.fromJson(result, InstallResult.class);
		deviceId = installResult.getDeviceId();
		
		Log.i("-------------------------------", "-------------> " + result);
		
		return deviceId;
		
	}
	
	public void trackerUnInstall(){
		ConnectInterface connectInterface = new HttpConnect();
		List<NameValuePair> pairs = new ArrayList<NameValuePair>();
		connectInterface.post(mContext.getString(R.string.APP_UNINSTALL), pairs);
	}
	
	
	

}
